package controllers

import (
	"gosync/models"
	"strings"
	"strconv"
)

type MachineController struct {
	BaseController
}





/*
目标机器列表管理
 */
func (this *MachineController) McList(){


	this.setTpl("machine.html")
}


/*
 *获取机器分页数据接口
 */
 func (this *MachineController) McListApi(){
	page, _ := this.GetInt("page")
 	datas, total := models.MachinePageList(page)

 	this.pageApiJson(datas, total, "", 0)

 }

 /*
 *添加机器
  */
  func (this *MachineController) AddMc(){

	this.setTpl("addmc.html")
  }


/*
*添加机器
*/
func (this *MachineController) AddMcDo(){
	username := strings.TrimSpace(this.GetString("username"))
	ipaddr := strings.TrimSpace(this.GetString("ip"))
	remark := strings.TrimSpace(this.GetString("remark"))

	params := models.Machine{
		Ip:ipaddr,
		Username:username,
		Remark:remark,
	}
	result := models.AddMc(params)

	if result != nil {
		this.ajaxReturn("", "添加失败:", 400)
	}else{
		this.ajaxReturn(map[string]string{"url":this.URLFor("MachineController.McList")}, "成功", 200)
	}
}

/*
*编辑机器
 */
func (this *MachineController) EditMc(){
	inputid := this.Input().Get("id")
	id, _ := strconv.Atoi(inputid)
	if id==0{
		this.goError("ID丢失！")
	}
	mc := models.Machine{}
	info,_ := mc.GetOne(id)

	this.Data["info"] = info
	this.setTpl("editmc.html")
}

func (this *MachineController) EditMcDo(){
	inputid := this.Input().Get("id")
	id, _ := strconv.Atoi(inputid)
	username := strings.TrimSpace(this.GetString("username"))
	ipaddr := strings.TrimSpace(this.GetString("ip"))
	remark := strings.TrimSpace(this.GetString("remark"))

	params := models.Machine{
		Id:id,
		Ip:ipaddr,
		Username:username,
		Remark:remark,
	}
	_, err := params.EditMc()

	if err != nil {
		this.ajaxReturn("", "修改失败", 400)
	}else{
		this.ajaxReturn(map[string]string{"url":this.URLFor("MachineController.McList")}, "成功", 200)
	}
}
func (this *MachineController) DelMcDo(){
	inputid := this.Input().Get("id")
	id, _ := strconv.Atoi(inputid)

	mc := models.Machine{}
	_, err := mc.DelMc(id)

	if err != nil {
		this.ajaxReturn("", "删除失败", 400)
	}else{
		this.ajaxReturn("", "成功", 200)
	}
}


func (this *MachineController) McDatas(){
	this.Ctx.WriteString("mcdatas")
}

